package com.ptmall.app.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebSettingsImpl;
import com.just.agentweb.IAgentWebSettings;
import com.ptmall.app.MainActivity;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.utils.Androidtojs;
import com.ptmall.app.view.TitleBarView;

public class WebActivity extends BaseMvpActivity {

    TitleBarView titlebar;

    String title;
    String url;
    private AgentWeb mAgentWeb;
    private LinearLayout mLinearLayout;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_web);
    }

    @SuppressLint("JavascriptInterface")
    @Override
    public void initViews() {
        title = getIntent().getStringExtra("title");
        url = getIntent().getStringExtra("url");

        mLinearLayout = (LinearLayout) findViewById(R.id.linearLayout);

        titlebar = (TitleBarView) findViewById(R.id.titlebar);
        titlebar.setText(title);

        titlebar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        mAgentWeb = AgentWeb.with(this)//传入Activity or Fragment
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                .useDefaultIndicator()// 使用默认进度条
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setAgentWebWebSettings(initSetting())
                .createAgentWeb()//
                .ready()
                .go(url);
        //Android 端 ， AndroidtoJs 是一个与js交互的类 ，里面有参数方法：callAndroid
        mAgentWeb.getJsInterfaceHolder().addJavaObject("WebViewJavascriptBridge", new Androidtojs(this));

    }

    @Override
    public void initEvents() {

    }

    private IAgentWebSettings initSetting() {
        IAgentWebSettings webSettings = new AgentWebSettingsImpl().toSetting(new WebView(this));
        webSettings.getWebSettings().setJavaScriptEnabled(true);// 启用支持JavaScript
        webSettings.getWebSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.getWebSettings().setUseWideViewPort(false);// 设置此属性，可任意比例缩放
        webSettings.getWebSettings().setAllowFileAccess(true);// 设置可以访问文件
        webSettings.getWebSettings().setBuiltInZoomControls(false);// 设置支持缩放
        webSettings.getWebSettings().setBlockNetworkImage(false);// 加载需要显示的网页
        webSettings.getWebSettings().setBlockNetworkLoads(false);
        webSettings.getWebSettings().setDomStorageEnabled(true);// ??
        webSettings.getWebSettings().setLoadWithOverviewMode(true);
        webSettings.getWebSettings().setAppCacheEnabled(false);// 使用缓存
        return webSettings;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        /**
         * 如果存在缓存问题，可以尝试放开清空cookie代码来解决问题
         * */
        //------清空所有Cookie  start-----
//        CookieSyncManager.createInstance(this);  //Create a singleton CookieSyncManager within a context
//        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
//        cookieManager.removeAllCookie();// Removes all cookies.
//        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now
//        mAgentWeb.getWebCreator().getWebView().setWebChromeClient(null);
//        mAgentWeb.getWebCreator().getWebView().setWebViewClient(null);
//        mAgentWeb.getWebCreator().getWebView().getSettings().setJavaScriptEnabled(false);
//        mAgentWeb.getWebCreator().getWebView().clearCache(true);
        //------清空所有Cookie  end-----

        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            view.loadUrl(url);
            return true;

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO Auto-generated method stub
            super.onPageFinished(view, url);

        }

    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
        }
        //上传 begin

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            uploadMessage = valueCallback;
            // openImageChooserActivity();
        }

        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            uploadMessage = valueCallback;
            // openImageChooserActivity();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            uploadMessage = valueCallback;
            // openImageChooserActivity();
        }

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            // openImageChooserActivity();
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {

        }
    };

}
